﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.EmpbasicService;
using System.Collections.ObjectModel;
using CommunitySystem.KaoHeService;

namespace CommunitySystem.PageView
{
    public partial class SYQMKHWindow : ChildWindow
    {
        private EmpBasicServiceClient empclient = new EmpBasicServiceClient();
        private KaoHeServiceClient kaoheclient = new KaoHeServiceClient();
        private Emp_SYQMKHModel OldModel = new Emp_SYQMKHModel();
        private Emp_SYQMKHFJModel jinshenatt = null;
        public SYQMKHWindow(Emp_SYQMKHModel Model)
        {
            InitializeComponent();

            OldModel = Model;
            OldModel.Attachment = new ObservableCollection<Emp_SYQMKHFJModel>();
          

            this.DataContext = OldModel;

            this.sphg.Visibility = Visibility.Collapsed;
            this.spbhg.Visibility = Visibility.Collapsed;
            this.spsy.Visibility = Visibility.Collapsed;
            this.spfj.Visibility = Visibility.Visible;
            List<string> khjg = new List<string>() { "合格", "不合格", "顺延试用期" };
            this.cbKHJG.ItemsSource = khjg;

            if (Model.KHStatus == "合格") this.cbKHJG.SelectedIndex = 0;
            if (Model.KHStatus == "不合格") this.cbKHJG.SelectedIndex = 1;
            if (Model.KHStatus == "顺延试用期") this.cbKHJG.SelectedIndex = 2;
            if (!string.IsNullOrEmpty(Model.KHStatus)) SFHG(Model.KHStatus);
            //考核结果选择条件
            this.cbKHJG.SelectionChanged += new SelectionChangedEventHandler(cbKHJG_SelectionChanged);

            //科室
            empclient.GetBianZhiModelCompleted += new EventHandler<EmpbasicService.GetBianZhiModelCompletedEventArgs>(Client_GetBianZhiModelCompleted);
            empclient.GetBianZhiModelAsync(Model.OrgID.ToString(), 0);

            _uploadClient.UploadFileCompleted += new EventHandler<PublicOfficialSelectionService.UploadFileCompletedEventArgs>(_uploadClient_UploadFileCompleted);

            kaoheclient.SYQMKH_SBCompleted += new EventHandler<CommunitySystem.KaoHeService.SYQMKH_SBCompletedEventArgs>(kaoheclient_SYQMKH_SBCompleted);
        }
        bool iscg = true;
        void kaoheclient_SYQMKH_SBCompleted(object sender, CommunitySystem.KaoHeService.SYQMKH_SBCompletedEventArgs e)
        {
            if (e.Result && iscg)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("上报成功！");
                iscg = false;
            }

            else
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("上报失败！");
                iscg = false;
            }

            this.DialogResult = true;
        }
        #region  科室
        void Client_GetBianZhiModelCompleted(object sender, EmpbasicService.GetBianZhiModelCompletedEventArgs e)
        {
            biaoti.ItemsSource = null;
            biaoti.ItemsSource = e.Result;
            if (biaoti.ItemsSource != null)
            {
                for (int i = 0; i < ((ObservableCollection<BianZhiModel>)biaoti.ItemsSource).Count; i++)
                {
                    if (((ObservableCollection<BianZhiModel>)biaoti.ItemsSource)[i].JiGouMingCheng == OldModel.KS)
                        biaoti.SelectedIndex = i;
                }
            }
        }
        private int keyongzhishu = 0;
        void gangwei_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ComboBox)sender).SelectedItem != null)
            {
                OldModel.KS = ((BianZhiModel)((((ComboBox)sender).SelectedItem))).JiGouMingCheng;

                    //if (model.DutyLevel == "乡科级正职（主任科员）" && model.DutyAttribute == "领导职务")
                    //    keyongzhishu = Convert.ToInt32(((BianZhiModel)((((ComboBox)sender).SelectedItem))).ZhengKeShiJi);
                    //if (model.DutyLevel == "乡科级正职（主任科员）" && model.DutyAttribute == "非领导职务")
                    //    keyongzhishu = Convert.ToInt32(((BianZhiModel)((((ComboBox)sender).SelectedItem))).ZhuRenShiJi);
                    //if (model.DutyLevel == "乡科级副职（副主任科员）" && model.DutyAttribute == "领导职务")
                    //    keyongzhishu = Convert.ToInt32(((BianZhiModel)((((ComboBox)sender).SelectedItem))).FuKeShiJi);
                    //if (model.DutyLevel == "乡科级副职（副主任科员）" && model.DutyAttribute == "非领导职务")
                    //    keyongzhishu = Convert.ToInt32(((BianZhiModel)((((ComboBox)sender).SelectedItem))).FuZhuRenShiJi);
                if (OldModel.DutyLevel == "乡科级副职（副主任科员）") 
                    keyongzhishu = Convert.ToInt32(((BianZhiModel)((((ComboBox)sender).SelectedItem))).FuZhuRenShiJi);

            }

        }
        #endregion
        /// <summary>
        ///   //考核结果选择条件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cbKHJG_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string sel=cbKHJG.SelectedItem.ToString();
            SFHG(sel);
        }

        private void SFHG(string sel)
        {
            if (sel == "合格")
            {
                this.sphg.Visibility = Visibility.Visible;
                this.spbhg.Visibility = Visibility.Collapsed;
                this.spsy.Visibility = Visibility.Collapsed;
                if (string.IsNullOrEmpty(OldModel.REbeDate)) OldModel.REbeDate = (DateTime.Now.Year.ToString() + "-07-01");
                OldModel.KHStatus = sel;
            }
            if (sel == "不合格")
            {
                this.sphg.Visibility = Visibility.Collapsed;
                this.spbhg.Visibility = Visibility.Visible;
                this.spsy.Visibility = Visibility.Collapsed;
            
                OldModel.KHStatus = sel;
            }
            if (sel == "顺延试用期")
            {
                this.sphg.Visibility = Visibility.Collapsed;
                this.spbhg.Visibility = Visibility.Collapsed;
                this.spsy.Visibility = Visibility.Visible;
         
                OldModel.KHStatus = sel;
            }
        }
        private bool Validate()
        {
            if (string.IsNullOrEmpty(OldModel.TLSJ))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请选择会议讨论时间！");
                return false;
            }
            if (string.IsNullOrEmpty(OldModel.KHStatus))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请选择考核结果！");
                return false;
            }
            else
            {
                if (OldModel.KHStatus == "合格")
                {
                    if (string.IsNullOrEmpty(OldModel.REbeDate))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("请选择任职定级时间！");
                        return false;
                    }
                    else if (Convert.ToDateTime(OldModel.REbeDate) < Convert.ToDateTime(OldModel.TLSJ))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("任职定级时间不能早于会议讨论时间！");
                        return false;
                    }
                    if (string.IsNullOrEmpty(OldModel.DutyLevel))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("请选择职务层次！");
                        return false;
                    }
                    if (string.IsNullOrEmpty(OldModel.KS))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("请选择科室！");
                        return false;
                    }
                    if (string.IsNullOrEmpty(OldModel.DutyNo))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("请选择职位！");
                        return false;
                    }

                    if (OldModel.Attachment.Where(p => p.Type == "考核表").ToList().Count() == 0)
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("请上传试用期满考核表！");
                        return false;
                    }
                    if ( OldModel.Attachment.Where(p => p.Type == "定级表").ToList().Count() == 0)
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("请上传公务员任职定级表！");
                        return false;
                    }
                }
                else if (OldModel.KHStatus == "不合格")
                {
                    if (string.IsNullOrEmpty(OldModel.BHGYY))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("请填写不合格原因！");
                        return false;
                    }
                    if (OldModel.Attachment.Where(p => p.Type == "考核表").ToList().Count() == 0)
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("请上传试用期满考核表！");
                        return false;
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(OldModel.SYQYSYY))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("请填写试用期延顺原因！");
                        return false;
                    }
                    if (string.IsNullOrEmpty(OldModel.SYQYSDate))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("请填写试用期延顺时间！");
                        return false;
                    }
                    else if (Convert.ToDateTime(OldModel.SYQYSDate) < Convert.ToDateTime(OldModel.TLSJ))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage("试用期延顺时间不能早于会议讨论时间！");
                        return false;
                    }
                }
            }
            
            return true;
        }
        private PublicOfficialSelectionService.PublicOfficialSelectionServiceClient _uploadClient =
            new PublicOfficialSelectionService.PublicOfficialSelectionServiceClient();
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
           // this.DialogResult = true;

            if (Validate())
            {
                OldModel.Status = "已上报";
                OldModel.ISZS = "是";
                if (OldModel.KHStatus == "不合格") OldModel.BZ = "不合格:" + OldModel.BHGYY;
                if (OldModel.KHStatus == "顺延试用期") OldModel.BZ = "顺延试用期:" + OldModel.SYQYSDate+" "+OldModel.SYQYSYY;

                //乡科级副职（副主任科员） 植树不足需二次判断
                if (OldModel.DutyLevel == "乡科级副职（副主任科员）")
                {
                    if (keyongzhishu > 0)
                    {
                        OldModel.ISZS = "是";
                        SB();
                    }
                    else
                    {

                        if (MessageBox.Show("该岗位职数已满，确定要进行上报吗？", "系统提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                        {
                            OldModel.ISZS = "否";
                            SB();
                        }
                    }
                }else
                    SB();
            }
        }

        private void SB()
        {
            if (files.Count > 0)
            {
                #region 上传文件
                foreach (var key in files.Keys)
                {
                    var file = files[key];
                    _uploadClient.UploadFileAsync(fileDictionary, file.DisplayName, file.Context[0], true, file);
                    file.Context.RemoveAt(0);

                }
                #endregion
            }
            kaoheclient.SYQMKH_SBAsync(OldModel);
        }
        void _uploadClient_UploadFileCompleted(object sender, PublicOfficialSelectionService.UploadFileCompletedEventArgs e)
        {
            var file = e.UserState as UploadFileInfo;
            if (file.Context.Count > 0)
            {
                _uploadClient.UploadFileAsync(fileDictionary, file.DisplayName, file.Context[0], false, file);
                file.Context.RemoveAt(0);
            }
            //kaoheclient.SYQMKH_SBAsync(OldModel);
        }
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        #region  方案上报
        private readonly string fileDictionary = "file";
        private Dictionary<string, UploadFileInfo> files = new Dictionary<string, UploadFileInfo>();
        
        private void hlb_Click(object sender, RoutedEventArgs e)
        {
            var hbtn=sender as HyperlinkButton;
            int tag=Convert.ToInt32(hbtn.Tag);

            var openFile = new OpenFileDialog() { Multiselect = false };
            if (openFile.ShowDialog() == true)
            {
                string GuidName = Guid.NewGuid().ToString("N");
                // files.Add(GuidName, openFile.File.OpenRead());
                UploadFileInfo uploadFile = new UploadFileInfo() { DisplayName = GuidName, Name = GuidName };
                var stream = openFile.File.OpenRead();
                uploadFile.Size = stream.Length / 16000;
                uploadFile.Context = new List<byte[]>();
                int b = 0;
                while (stream.Position > -1 && stream.Position < stream.Length)
                {
                    if (stream.Length - stream.Position >= 16000)
                    {
                        b = 16000;
                    }
                    else
                    {
                        b = (int)(stream.Length - stream.Position);
                    }

                    byte[] filebyte = new byte[b];
                    stream.Read(filebyte, 0, b);
                    uploadFile.Context.Add(filebyte);
                }
                stream.Close();
                files.Add(GuidName, uploadFile);
                StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal, VerticalAlignment = System.Windows.VerticalAlignment.Center };
                sp.Children.Add(new TextBlock() { Text = openFile.File.Name, });
                Image img = new Image() { Cursor = Cursors.Hand, Height = 15, Width = 15, Margin = new Thickness(5, 0, 0, 0) };
                img.Source = new System.Windows.Media.Imaging.BitmapImage(
                    new Uri("/CommunitySystem;component/Images/ViewDesign/delete.png",
                        UriKind.RelativeOrAbsolute));
                sp.Children.Add(img);

                if (OldModel.Attachment == null)
                    OldModel.Attachment = new ObservableCollection<Emp_SYQMKHFJModel>();
                var att = new Emp_SYQMKHFJModel() { realname = openFile.File.Name, filename = GuidName, Key = fileDictionary,Type=tag==1?"考核表":"定级表" };
                OldModel.Attachment.Add(att);
                jinshenatt = OldModel.Attachment.First();
                img.MouseLeftButtonDown += (sender1, e1) =>
                {
                    wp.Children.Remove(sp);
                    files.Remove(GuidName);
                    OldModel.Attachment.Remove(att);
                    jinshenatt = null;
                };
                wp.Children.Add(sp);
            }
        }
        #endregion

    
    }
}

